package com.bear.newsset.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bear.newsset.R;
import com.bear.newsset.entity.NewsLableEntity;
import com.bear.newsset.entity.NewsListEntity;
import com.bear.newsset.entity.NewsParamEntity;
import com.bear.newsset.mvp.presen.HomePresen;
import com.bear.newsset.mvp.view.HomeView;
import com.bear.newsset.ui.activity.SearchActivity;
import com.bear.newsset.util.DOM;
import com.bear.newsset.util.LogUtils;
import com.bear.newsset.widget.NewsListRecyclerView;
import com.bear.newsset.widget.NewsView;
import com.bear.newsset.widget.NewsViewPager;
import com.bear.newsset.widget.SearchView;
import com.bear.newsset.widget.SiteTableView;
import com.ybear.ybmvp.annotations.BindView;
import com.ybear.ybmvp.annotations.Presen;
import com.ybear.ybmvp.view.v4.YBFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.bear.newsset.util.Constant.DOM_ID_SITE_POSITION;

/**
 * 首页Fragment
 */
public class HomeFragment extends YBFragment implements HomeView {
    @Presen
    private HomePresen mPresen;

    @BindView(R.id.home_search_view)
    private SearchView vSearch;

    @BindView(R.id.home_site_table_view)
    private SiteTableView vSiteTable;

    @BindView(R.id.home_viewpage_news_view)
    private NewsViewPager vNewsPager;

    private List<View> pageList;
    private ThisHandler mThisHandler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initListener();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mThisHandler = new ThisHandler(this);
        //设置背景颜色
        setBackgroundResource( R.color.colorChild );
        //获取新闻类别列表
        mPresen.getNewsLableList();
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        //搜索栏点击事件监听器
        vSearch.setOnSearchClickListener(view -> {
            //打开搜索栏页面
            startActivity(new Intent(view.getContext(), SearchActivity.class));
        });

        //新闻分类列表点击事件监听器
        vSiteTable.setOnItemSelectedListener((radioGroup, config, position) -> {
            //选中新闻列表的页面
            vNewsPager.setCurrentItem(position);
            DOM.getInstance().setResult(DOM_ID_SITE_POSITION, position);
        });

        //页面滑动事件监听器
        vNewsPager.setOnPageChangeAdapter(new NewsViewPager.OnPageChangeAdapter() {
            @Override
            public void onPageSelected(View v, int i) {
                super.onPageSelected(v, i);
                //获取当前页面的新闻列表
                NewsListRecyclerView newsListView = ((NewsView) v).getNewsListView();
                //仅当列表不存在时才传入获取列表的参数
                if( !newsListView.isDataFirst() ) mPresen.selectNewsLable(newsListView, i);
                //当前选择的分类
                vSiteTable.setItemSelected(i);
            }
        });
    }

    /**
     * 设置背景颜色
     * @param resId     颜色id
     */
    private void setBackgroundResource(@DrawableRes int resId) {
        if( getView() != null ) getView().setBackgroundResource( resId );
    }

    /**
     * 选中的新闻标签
     * @param mainLable     主标签
     * @param childLables   子标签
     */
    @Override
    public void selectNewsLable(NewsListRecyclerView v,
                                NewsLableEntity mainLable, List<NewsLableEntity> childLables) {

        long mainLableId = mainLable.getLableId();
        List<NewsListEntity> sqlList = mPresen.queryNewsListSql( mainLableId );

        //从数据库查询新闻列表
        if( sqlList != null ) v.setNewsDataList(mainLableId, sqlList);
        //请求新闻数据
        v.setNewsParam(
                new NewsParamEntity()
                        .setMainLableId( mainLableId )  //设置新闻参数的主标签id
        ).requestNewsData();

        LogUtils.d("selectNewsLable",
                "MianLableId:" + mainLable.getLableId() +
                        " ChildLablesSize:" + childLables.size());
    }

    /**
     * 新闻标签列表
     * @param map   列表
     */
    @Override
    public void newsLableList(Map<NewsLableEntity, List<NewsLableEntity>> map) {
        List<SiteTableView.ItemConfig> configList = new ArrayList<>();
        //主标签列表
        List<NewsLableEntity> mainLables = Arrays.asList(
                map.keySet().toArray( new NewsLableEntity[0])
        );
        //初始化选项卡数据
        for( NewsLableEntity e : mainLables ) {
            SiteTableView.ItemConfig ic = new SiteTableView.ItemConfig();
            ic.setItemText( e.getLable() );
            ic.setTextUnCheckColor( R.color.colorWhite );
            configList.add(ic);
        }
        //设置分类列表的Item
        vSiteTable.setItemList( configList );

        //空数据提示错误
        if( mainLables.size() == 0 ) mThisHandler.sendEmptyMessage(100);
        //获取新闻页面列表
        pageList = mPresen.getNewsPagerList( mainLables );
        //设置页面数据
        mThisHandler.sendEmptyMessage( 10 );
    }

    @Override
    public void showToast(String text) {
        Message msg = Message.obtain();
        Bundle b = new Bundle();
        b.putString("SHOW_TOAST_TEXT", text);
        msg.what = 999;
        msg.setData( b );
        mThisHandler.sendMessage( msg );
    }

    /**
     * Handler
     */
    private static class ThisHandler extends Handler {
        private HomeFragment mFragment;
        private Context mContext;
        ThisHandler(@NonNull HomeFragment mFragment) {
            super(Looper.getMainLooper());
            this.mFragment = mFragment;
            mContext = mFragment.getContext();
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String toastText = null;
            int toastLen = Toast.LENGTH_SHORT;
            Bundle data = msg.getData();
            switch ( msg.what ) {
                case 10:     //新闻页面适配器
                    //设置页面数据
                    mFragment.vNewsPager.setData( mFragment.pageList );
                    break;
                case 100:   //服务器维护提示
                    toastText = "服务器维护中...";
                    toastLen = Toast.LENGTH_LONG;
                    break;
                case 999:
                    if( data == null ) break;
                    toastText = data.getString("SHOW_TOAST_TEXT");
                    break;
            }

            if( toastText != null ) {
                Toast.makeText(mContext, toastText, toastLen).show();
            }
        }
    }
}
